package cn.donting.web.desktop.sys.controller;

import cn.donting.web.desktop.core.Application;
import cn.donting.web.desktop.core.app.AppManager;
import cn.donting.web.desktop.core.app.FileSysManger;
import cn.donting.web.desktop.core.configuration.StaticFileConfiguration;
import cn.donting.web.desktop.core.dao.OpenFileRepository;
import cn.donting.web.desktop.core.domain.ResponseEntity;
import cn.donting.web.desktop.core.domain.Wap;
import cn.donting.web.desktop.core.entity.AppInfo;
import cn.donting.web.desktop.core.entity.OpenFile;
import cn.donting.web.desktop.top.file.FileOpen;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;

@RestController
@RequestMapping("/sys/file")
@Slf4j
public class FileController {

    @Autowired
    FileSysManger fileSysManger;
    @Autowired
    OpenFileRepository openFileRepository;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    @Qualifier("appManager")
    AppManager appManager;

    /**
     * 获取文件的图标
     *
     * @param filePath
     * @param request
     * @param response
     * @throws IOException
     * @see cn.donting.web.desktop.core.app.FileSysManger
     * @see cn.donting.web.desktop.core.configuration.StaticFileConfiguration
     */
    @GetMapping("/icon")
    public void icon(String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            response.setStatus(404);
            return;
        }
        OpenFile openFile;
        String extName;
        //是否是文件夹
        if (file.isDirectory()) {
            extName = FileOpen.directory;
        } else {
            extName = FileUtil.extName(file);
        }
        if ("wap".equalsIgnoreCase(extName)) {
            try {
                Wap wap = objectMapper.readValue(file, Wap.class);
                AppInfo appInfo = appManager.getAppInfo(wap.getId());
                String icon = appInfo.getIcon();
//                icon = AppManager.APP_ICON + File.separator + icon;
                response.sendRedirect(StaticFileConfiguration.APP_ICON_URL + icon);
                return;
            } catch (Exception ex) {
                log.warn(ex.getMessage(), ex);
                //出错extName ==未知
                extName = FileOpen.unknown;
            }
        }
        //获取默认 图标
        openFile = openFileRepository.findByExtNameAndDefaultValue(extName, true);
        if (openFile == null) {
            //获取匹配的第一个 图标
            openFile = openFileRepository.findFirstByExtName(extName);
        }
        if (openFile == null) {
            extName = FileOpen.unknown;
            openFile = openFileRepository.findFirstByExtName(extName);
        }
        //static icon   sys/fileIcon
        response.sendRedirect(StaticFileConfiguration.FILE_ICON_URL + openFile.getFileName());
    }


    /**
     * 打开文件
     *
     * @param filePath
     * @param httpServletResponse
     * @throws IOException
     */
    @GetMapping("/open")
    public void open(String filePath, HttpServletResponse httpServletResponse) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            log.warn("文件不存在:[{}]", filePath);
            httpServletResponse.sendRedirect("/error/file/NotFoundOpenFileApp.html?appId=0&filePath=" + filePath);
            return;
        }

        if (!file.isDirectory()&&FileUtil.extName(file).equalsIgnoreCase(FileSysManger.WAP)) {
            openWap(filePath, httpServletResponse);
            return;
        }
        OpenFile openFIle = fileSysManger.getOpenFIle(file);
        if (openFIle == null) {
            httpServletResponse.sendRedirect("/error/file/NotFoundOpenFileApp.html?appId=0&filePath=" + filePath);
            return;
        }

        if (!appManager.isRunning(openFIle.getAppId())) {
            try {
                appManager.startApp(openFIle.getAppId());
            } catch (Exception e) {
                log.error("app 启动失败");
                log.error(e.getMessage(), e);
                String msg = StrUtil.format("app[{}]启动失败：{}", openFIle.getAppId(), e.getMessage());
                String path = StrUtil.format("/sys/app/error?appId={}&msg={}", Application.sysAppId, msg);
                httpServletResponse.sendRedirect(path);
            }
        }
        String path = StrUtil.format("{}?filePath={}&appId={}", openFIle.getOpenFileUrl(), filePath, openFIle.getAppId());
        httpServletResponse.sendRedirect(path);
        return;
    }


    /**
     * 打开wap文件
     *
     * @param filePath
     * @param response
     */
    @GetMapping("/open/wap")
    public void openWap(String filePath, HttpServletResponse response) {
        File file = new File(filePath);
        try {
            Wap wap = objectMapper.readValue(file, Wap.class);
            Long id = wap.getId();
            String index = appManager.getAppInfo(id).getIndex();
            String path = StrUtil.format(index + "?appId={}", id);
            response.sendRedirect(path);
        } catch (IOException e) {
            //TODO: 异常
            log.error(e.getMessage(), e);
        }
    }

}
